package com.frxuexi.sign.view

import androidx.activity.viewModels
import androidx.lifecycle.lifecycleScope
import com.alibaba.android.arouter.facade.annotation.Route
import com.blankj.utilcode.util.SPUtils
import com.blankj.utilcode.util.TimeUtils
import com.blankj.utilcode.util.ToastUtils
import com.frxuexi.lib_base.entity.SignBeanItem
import com.frxuexi.lib_base.http.Const
import com.frxuexi.lib_base.http.RequestType
import com.frxuexi.lib_base.mvi.BaseActivity
import com.frxuexi.lib_base.mvi.UiState
import com.frxuexi.lib_base.utils.ArouterManager
import com.frxuexi.lib_base.utils.DateTimeUtils
import com.frxuexi.sign.SignIntent
import com.frxuexi.sign.SignViewModel
import com.frxuexi.sign.databinding.ActivitySignBinding
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.launch
import java.util.Timer
import kotlin.concurrent.timerTask

@Route(path = "/sign/SignActivity")
@AndroidEntryPoint
class SignActivity : BaseActivity<ActivitySignBinding, SignIntent, SignViewModel>() {
    override val binding: ActivitySignBinding by lazy { ActivitySignBinding.inflate(layoutInflater) }
    override val vm: SignViewModel by viewModels<SignViewModel>()

    var timer:Timer?=null
    override fun initData() {
        lifecycleScope.launch {
            vm.uiState.collect{
                when(it){
                    is UiState.onSuccess<*> ->{
                        when(it.type){
                            RequestType.DEFAULT->{
                                val items = it.data as Collection<SignBeanItem>
                                val item = items.sortedByDescending { it.id }.get(0)
                                if(item.morningCheckIn.split(" ")[0]==DateTimeUtils.getDate(System.currentTimeMillis())){//打了上班卡
                                    if(item.afternoonCheckIn.isNotEmpty()){//下班打过卡
                                        binding.btnSign.isEnabled=false
                                    }else{//没打下班卡
                                        binding.signTvdaka.setText("下班打卡")
                                        binding.signTvtime.setText("14:00-18:00")
                                    }
                                }
                            }
                            RequestType.ADD->{
                                val item = it.data as SignBeanItem
                                ToastUtils.showLong("打卡成功")
                                if(binding.signTvdaka.text.toString()=="上班打卡"){
                                    binding.signTvdaka.setText("下班打卡")
                                    binding.signTvtime.setText("14:00-18:00")
                                    SPUtils.getInstance().put("sid",item.id!!)
                                    SPUtils.getInstance().put("stime",item.morningCheckIn)
                                    SPUtils.getInstance().put("status",item.status)
                                }else{
                                    binding.btnSign.isEnabled=false
                                }
                            }

                            else -> {}
                        }

                    }

                    else -> {}
                }
            }
        }
    }

    override fun initView() {
        vm.sendIntent(SignIntent.getSings(SPUtils.getInstance().getInt(Const.UID,-1)))

        binding.conLocation.setOnClickListener {
            ArouterManager.nav(this,"/sign/MapActivity")
        }

        binding.signList.setOnClickListener {
            ArouterManager.nav(this,"/sign/SignListActivity")
        }

        lifecycleScope.launch(Dispatchers.IO) {
            timer= Timer()
            timer?.schedule(timerTask {
                lifecycleScope.launch(Dispatchers.Main) {
                    binding.signTime.setText(DateTimeUtils.getTime(System.currentTimeMillis()))
                }
            },0,1000)
        }

        val millis = System.currentTimeMillis()
        val week = TimeUtils.getChineseWeek(millis).replace("周", "星期")
        val date =
            DateTimeUtils.getDate(millis).replaceFirst("-", "年").replaceFirst("-", "月").plus("日")
        binding.signDate.setText("${date} ${week}")

        binding.btnSign.setOnClickListener {
            val dateTime = DateTimeUtils.getDateTime(System.currentTimeMillis())

            if(binding.signTvdaka.text.toString()=="上班打卡"){
                var status="正常"
                if(dateTime.split(" ")[1]>"09:00:00"){
                    status="迟到"
                }
                val item = SignBeanItem(
                    "",
                    SPUtils.getInstance().getString("loc", ""),
                    null,
                    "八维学院",
                    dateTime,
                    status,
                    SPUtils.getInstance().getInt(Const.UID, -1)
                )
                vm.sendIntent(SignIntent.sign(item))
            }else{
                var status="正常"
                if(dateTime.split(" ")[1]<"18:00:00"){
                    status="早退"
                }
                val item = SignBeanItem(
                    dateTime,
                    SPUtils.getInstance().getString("loc", ""),
                    SPUtils.getInstance().getInt("sid"),
                    "八维学院",
                    SPUtils.getInstance().getString("stime"),
                    "${SPUtils.getInstance().getString("status")},${status}",
                    SPUtils.getInstance().getInt(Const.UID, -1)
                )
                vm.sendIntent(SignIntent.sign(item))
            }
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        timer?.cancel()
        timer=null
    }

}